<template>
  <el-dialog :visible.sync="dialogVisible" width="80%" class="chart-detail-dialog" :append-to-body="true"
    :modal-append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleClose">
    <div class="dialog-content">
      <div class="line-chart-section" v-if="chartType === 'double' || chartType === 'line'" :class="{
        'height_600': chartType === 'line',
        'h_300': chartType === 'double'
      }">
        <bi-line-chart :title="lineChartTitle" :chart-data="lineChartData" :options="lineChartOptions"
          @Change="dialogChange" ref="biLineChartFn" :show="chartType === 'line'" @dataZoom="dataZoom"
          :day="lineChartData.day" @update:day="newDay => lineChartData.day = newDay" />
      </div>
      <div class="bar-chart-section" v-if="chartType === 'double' || chartType === 'bar'" :class="{
        'height_600': chartType === 'bar',
        'h_300': chartType === 'double'
      }">
        <div class="bar-chart-header">
          <!-- <span class="current-level-title">{{ currentLevelTitle }}</span> -->
          <button v-if="currentLevel > 0" class="back-button" @click="handleBack"><i class="el-icon-fanhuishangyiji"
              style="color: #666;margin-right: 5px;" />返回</button>
        </div>
        <bi-bar-chart :title="barChartTitle" :chart-data="currentBarChartData" :options="barChartOptions"
          @bar-click="handleBarClick" ref="biBarChartFn" />
      </div>
    </div>
  </el-dialog>
</template>

<script>
import BiLineChart from './LineChart.vue'
import BiBarChart from './BarChart.vue'
import { getSalesLineChartData } from '@/api/user'
import data from 'china-area-data'

export default {
  name: 'BiChartDetailDialog',
  components: {
    BiLineChart,
    BiBarChart
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    chartType: {
      type: String,
      default: "double"
    },
    title: {
      type: String,
      required: true
    },
    lineChartTitle: {
      type: String,
      default: '品牌销售完成金额'
    },
    lineChartData: {
      type: Object,
      required: true
    },
    lineChartOptions: {
      type: Object,
      default: () => ({})
    },
    barChartTitle: {
      type: String,
      default: '品牌销售排名'
    },
    barChartData: {
      type: Object,
      required: true
    },
    barChartOptions: {
      type: Object,
      default: () => ({})
    },
    detailDialogNameList: {
      type: Array,
      default: () => []
    },
    colorList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentLevel: 0,
      dataStack: [],
      currentBarChartData: null,
      currentLevelTitle: '品牌销售排名',
      localChartData: null,
      mergedChartData: null,
      currentLeveName:[]
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    processedLineChartData() {
      if (!this.lineChartData) return null;
      try {
        let newData = JSON.parse(JSON.stringify(this.lineChartData));
        if (this.localChartData && this.lineChartData.dateStr !== this.localChartData.dateStr) {
          // 合并xAxis
          if (Array.isArray(newData.xAxis) && Array.isArray(this.localChartData.xAxis)) {
            newData.xAxis = [...newData.xAxis, ...this.localChartData.xAxis];
          }
          // 合并series
          if (Array.isArray(newData.series) && Array.isArray(this.localChartData.series)) {
            newData.series = newData.series.map((newSeries, index) => {
              const oldSeries = this.localChartData.series[index];
              if (oldSeries && Array.isArray(oldSeries.data) && Array.isArray(newSeries.data)) {
                return {
                  ...oldSeries,
                  ...newSeries,
                  data: [...newSeries.data, ...oldSeries.data]
                };
              }
              return newSeries;
            });
          }
        }
        
        this.localChartData = newData;
        return newData;
      } catch (error) {
        console.error('数据合并过程中发生错误:', error);
        return this.lineChartData;
      }
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          console.log(val,'valval');
          
          this.resetChartData()
        }
      }
    },
    lineChartData: {
      deep: true,
      handler(val) {        
        if (val && this.$refs.biLineChartFn) {
          // 清除之前的定时器
          if (this.debounceTimer) {
            clearTimeout(this.debounceTimer);
          }
          
          // 设置新的防抖定时器
          this.debounceTimer = setTimeout(() => {

          }, 300);
        }
      }
    },
    barChartData(newValue) {
      console.log(newValue,'-----监听');
      
      if (newValue && this.$refs.biBarChartFn) {
        console.log('监听');
      }
    }
  },
  methods: {
    handleClose() {
      this.$emit('close')
      if (this.$refs.biLineChartFn) this.$refs.biLineChartFn.reset()
    },
    async handleBarClick(params) {
      if (this.barChartTitle !== '品牌销售排名') return
      if (this.currentLevel < 2) {
        this.currentLevel++
        const nextLevelData = await this.getNextLevelData(params.name)
        if (nextLevelData) {
          this.dataStack.push({
            data: this.currentBarChartData,
            title: this.currentLevelTitle
          })
          this.currentBarChartData = {
            xAxis: nextLevelData.xAxis,
            series: nextLevelData.series
          }
          this.currentLevelTitle = `${params.name}销售详情`
        }
      }
    },
    handleBack() {
      if (this.currentLevel > 0) {
        const previousData = this.dataStack.pop()
        this.currentBarChartData = previousData.data
        this.currentLevelTitle = previousData.title
        this.currentLevel--
        if(this.currentLevel === 0) this.currentLeveName = []
        this.$emit('handleBack', {
          currentLeve: this.currentLevel,
          name:this.currentLeveName
        })
      }
    },
    resetChartData() {
      this.currentLevel = 0
      this.dataStack = []
      this.currentBarChartData = this.barChartData
      this.currentLevelTitle = '品牌销售排名'
      this.$nextTick(() => {
              this.$refs.biLineChartFn?.resetChart()              
              this.$refs.biLineChartFn?.handleResize()
              this.$refs.biLineChartFn?.updateChart();
              this.$refs.biBarChartFn?.resetChart()
              this.$refs.biBarChartFn?.handleResize()
              this.$refs.biBarChartFn?.updateChart();
            });
    },
    async getNextLevelData(name) {
      const currentLevelObj = {
        0: 'brand',
        1: 'series',
        2: 'product_level'
      }
      // console.log(this.currentLevel);
      
      const data = JSON.parse(localStorage.getItem('data'))
      // console.log(data, '----data');
      let returnData
      await getSalesLineChartData('getSalesBrandBarChartData', undefined, data.cityLevel, data.cityName, data.newOrgType, data.newOrgName, currentLevelObj[this.currentLevel], name).then(res => {
        const { data } = res;
        returnData ??= { xAxis: data.xdata, series: data.series }
        this.currentLeveName.push(name)
        console.log(this.currentLeveName,'-----this.currentLeveName');

        this.$emit('handleBarClick', {
          name,
          currentLevel:currentLevelObj[this.currentLevel]
        })
      }).catch(error => {
        console.error(`获取数据失败: ${error}`);
      });
      return returnData
    },
    dialogChange(event) {
      if(this.lineChartData) {
        this.lineChartData.xAxis = []
        this.lineChartData.series.forEach(item => {item.data = []});
      }
      this.$emit('dialogSelectedStepChange', event)
    },
    dataZoom(event) {
      this.$emit('dialogDataZoom', event)
    }
  }
}
</script>

<style lang="scss" scoped>
.back-button {
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.height_600 {
  height: 600px !important;
}

.h_300 {
  height: 330px !important;
}

.detailDialogName_box {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding: 0 10px;
  column-gap: 30px;

  &_item {
    color: #666666;
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    column-gap: 4px;
  }
}


.chart-detail-dialog {

  :deep(.el-dialog__wrapper) {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    margin: 0;
    z-index: 2000;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .dialog-content {
    .line-chart-section {
      height: 300px;
      margin-bottom: 20px;
    }

    .bar-chart-section {
      height: 300px;

      .bar-chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        // margin-bottom: 10px;

        .current-level-title {
          margin-left: 10px;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
  }
}
</style>